package org.grow.common.interceptor;

import org.grow.common.exception.NoAuthException;
import org.grow.common.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/20
 */
@Component
//采用 spring的拦截器 而不是过滤器
public class AuthInterceptor implements HandlerInterceptor {
    public static String getCurrentUser(){
        return (String) RequestContextHolder.currentRequestAttributes().getAttribute("username",0);
    }
    public static String getCurrentToken(){
        return (String) RequestContextHolder.currentRequestAttributes().getAttribute("token",0);
    }
    @Autowired
    private JwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器生效 " + request.getRequestURI());
        String authorization = request.getHeader("Authorization");
        if (!StringUtils.hasText(authorization)) {
            throw new NoAuthException("please login first");
        }
        System.out.println("token is " + authorization);
        String pureToken = authorization.replace("Bearer ", "");

        Map<String, Object> map = jwtService.parseToken(pureToken);
        System.out.println(" current user info " + map);
        Object username = map.get("username");
//        request.setAttribute("currentUser", username);
        RequestContextHolder.currentRequestAttributes().setAttribute("username",username,0);
        RequestContextHolder.currentRequestAttributes().setAttribute("token",pureToken,0);
// load current user
        return true;
    }
}
